package com.ellecity06.debugtools.ui.fragment.request.pagination

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.ellecity06.debugtools.db.dao.RequestDao
import com.ellecity06.debugtools.db.entity.RequestEntity

/**
 * @author ellecity06
 * @time 2023/4/20 11:09
 * @des
 */
internal class DebugRequestPagingSource(private val dao: RequestDao) : PagingSource<Int, RequestEntity>() {
    override fun getRefreshKey(state: PagingState<Int, RequestEntity>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RequestEntity> {
        val page = params.key ?: 0
        return try {
            val entities = dao.getRequestList(params.loadSize, page * params.loadSize)

            LoadResult.Page(
                data = entities,
                prevKey = if (page == 0) null else page - 1,
                nextKey = if (entities.size < params.loadSize || entities.isEmpty()) null else page + 1
            )

        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}